<%@ page language="java" import="org.apache.commons.lang.StringUtils" pageEncoding="UTF-8"%>
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ page import="java.io.FileInputStream" %>
<%@ page import="java.io.OutputStream" %>
<%@ page import="java.io.RandomAccessFile" %>
<%@ page import="up7.utils.PathTool" %>
<%
out.clear();
/*
	下载文件块，针对于合并后的文件处理
	相关错误：
		getOutputStream() has already been called for this response
			解决方法参考：http://stackoverflow.com/questions/1776142/getoutputstream-has-already-been-called-for-this-response
	更新记录：
		2015-05-13 创建
		2017-05-06 增加业务逻辑数据，简化处理逻辑
		2017-05-14 优化逻辑
		2017-05-21 支持下载文件块（未合并）
		2017-08-15 精简参数，取消对redis的操作
*/
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

String pathSvr 		= request.getHeader("pathSvr");
String blockPath 	= request.getHeader("blockPath");
String blockIndex 	= request.getHeader("blockIndex");//基于1
String blockOffset	= request.getHeader("blockOffset");//基于块的偏移位置，基于0
String fileOffset	= request.getHeader("fileOffset");//基于文件的偏移位置
String blockSize	= request.getHeader("blockSize");//当前块大小
blockPath			= PathTool.url_decode(blockPath);

if (	StringUtils.isEmpty(blockIndex)
	||	StringUtils.isEmpty(blockOffset)
	||	StringUtils.isEmpty(blockSize)
	||	StringUtils.isEmpty(blockPath)
	)
{	
	System.out.println("blockPath:".concat(blockPath));
	System.out.println("blockIndex:".concat(blockIndex));
	System.out.println("blockOffset:".concat(blockOffset));
	System.out.println("blockSize:".concat(blockSize));
	System.out.println("f_down.jsp 业务逻辑参数为空。");
	response.setStatus(500);
	return;
}

RandomAccessFile raf = new RandomAccessFile(blockPath,"r");
FileInputStream in = new FileInputStream( raf.getFD() );

long dataToRead = Long.parseLong(blockSize);
response.setContentType("application/x-download");
response.setHeader("Pragma","No-cache");  
response.setHeader("Cache-Control","no-cache");  
response.setDateHeader("Expires", 0);
response.addHeader("Content-Length",blockSize );

OutputStream os = null;
try
{
	os = response.getOutputStream();
	long offset_begin = Long.parseLong(blockOffset);
	in.skip(offset_begin);//定位索引
	
	byte[] buffer = new byte[1048576];//1MB
	int len = 0;	
	
	while( dataToRead > 0 )
	{
		len = in.read(buffer,0,Math.min(1048576,(int)dataToRead));		
		os.write(buffer, 0, len);
		os.flush();
		response.flushBuffer();
		buffer = new byte[1048576];
		dataToRead = dataToRead - len;
	}
	os.close();		
	os = null;
	
	out.clear();
	out = pageContext.pushBody();
}
catch(Exception e){response.setStatus(500);}
finally
{	
	if(os != null)
	{
		os.close();		
		os = null;
	}
	out.clear();
	out = pageContext.pushBody();
}
in.close();
in = null;%>